<template>
  <Dialog title="模型上传" @handle-confirm="handleConfirm">
    <el-form ref="formRef" :model="form" label-width="auto" label-suffix="：">
      <el-form-item label="模型名称" prop="name">
        <el-input v-model="form.modelName" placeholder="请输入模型名称"
      /></el-form-item>
      <el-form-item label="选择模型" prop="zone">
        <div>
          <el-button @click="handleCheck">选择模型</el-button>
          <span class="fileName" v-if="form.file">{{ form.file.name }}</span>
          <p class="tips">提示：演示只支持glb模型</p>
        </div>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import { useFileDialog } from '@vueuse/core'
import { ref } from 'vue'

import Dialog from '@/components/Dialog/index.vue'
import { uploadModel } from '@/http/models'

interface EmitsType {
  (e: 'success'): void
}
const emit = defineEmits<EmitsType>()

const form = ref<{
  modelName: string
  file: File | null
}>({
  modelName: '',
  file: null,
})

const { onChange, open } = useFileDialog({
  accept: '.glb',
})

onChange((files) => {
  if (!files?.length) {
    return
  }
  form.value.file = files[0]
})
const handleCheck = () => {
  open()
}

const handleConfirm = async () => {
  if (!form.value.file) {
    return
  }
  const formData = new FormData()
  formData.append('file', form.value.file)
  formData.append('displayName', form.value.modelName)
  const res = await uploadModel(formData)
  console.log('res:', res)
  emit('success')
}
</script>

<style scoped lang="scss">
.tips {
  line-height: 1.5;
}
.fileName {
  margin-left: 10px;
}
</style>
